package homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author DCSGO
 * @version 1.0
 * (1)编写一个接收端A，和一个发送端B，使用UDP协议完成
 * (2)接收端在8888端口等待接收数据(receive)
 * (3)发送端向接收端发送数据“四大名著是哪些？"
 * (4)接收端接收到发送端发送的问题后，返回“四大名著是<<红楼梦>>..."，否则返回 what?
 * (5)接收端和发送端程序退出
 */
public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(8888);
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

        System.out.println("等待询问...");
        datagramSocket.receive(datagramPacket);
        String s = new String(bytes, 0, datagramPacket.getLength());
        System.out.println(s);
        byte[] ans;
        if (s.equals("四大名著是哪些？")) {
            ans = "四大名著是<<红楼梦>>...".getBytes();
        } else {
            ans = "what?".getBytes();
        }
        DatagramPacket datagramPacket1 =
                new DatagramPacket(ans, ans.length, InetAddress.getByName("192.168.124.10"), 9999);
        datagramSocket.send(datagramPacket1);
        datagramSocket.close();
        System.out.println("问题已回答！");

        /*
         * 等待询问...
         * 四大名著是哪些？
         * 问题已回答！
         *
         * 进程已结束，退出代码为 0
         */
    }
}
